package org.cainiao.api.lark.impl.reactive.docs.space.folder;

import lombok.RequiredArgsConstructor;
import org.cainiao.api.lark.dto.request.docs.space.folder.ListItemsInFolderRequest;
import org.cainiao.api.lark.dto.response.LarkDataResponse;
import org.cainiao.api.lark.dto.response.docs.space.folder.LarkFilePage;
import org.cainiao.api.lark.dto.response.docs.space.folder.LarkFolderMeta;
import org.cainiao.api.lark.impl.util.converter.ResponseConverter;
import org.cainiao.api.lark.reactive.docs.space.folder.Folder;
import org.cainiao.common.util.QueryParameterUtil;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.Map;

import static org.cainiao.api.lark.util.Util.DRIVE_MODULE_URI;

/**
 * 靠 RestOperations 切换 HTTP 客户端<br />
 * <p>
 * Author: Cai Niao(wdhlzd@163.com)<br />
 */
@RequiredArgsConstructor
public class WebClientFolder implements Folder {

    private final WebClient webClient;
    private final String baseUrl;
    private final ResponseConverter responseConverter;

    @Override
    public Mono<LarkDataResponse<LarkFilePage>> listItemsInFolder(ListItemsInFolderRequest listItemsInFolderRequest) {
        String url = String.format("%s%s/files%s",
            baseUrl, DRIVE_MODULE_URI, QueryParameterUtil.toQueryString(listItemsInFolderRequest));
        return webClient.get()
            .uri(url)
            .accept(MediaType.APPLICATION_JSON)
            .retrieve()
            .bodyToMono(new ParameterizedTypeReference<Map<String, Object>>() {
            })
            .map(responseConverter::convertToLarkFilePageResponse);
    }

    @Override
    public Mono<LarkDataResponse<LarkFolderMeta>> getFolderMeta(String folderToken) {
        String url = String.format("%s/drive/explorer/v2/folder/%s/meta", baseUrl, folderToken);
        return webClient.get()
            .uri(url)
            .accept(MediaType.APPLICATION_JSON)
            .retrieve()
            .bodyToMono(new ParameterizedTypeReference<Map<String, Object>>() {
            })
            .map(responseConverter::convertToLarkFolderMetaResponse);
    }
}
